package com.lemon.exam.common.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.lemon.exam.common.constant.ApiConst;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * ObjectMapper 配置 JSON 解析
 *
 * @author Lemon
 * @since 2025/3/24 11:47
 */
@Configuration
public class JacksonConfiguration {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        //1.注册 JavaTimeModule 以支持 Java 8 日期时间类型
        JavaTimeModule javaTimeModule = new JavaTimeModule();

        //2.为 LocalDateTime、LocalDate 和 LocalTime 配置格式化规则
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(ApiConst.DATE_FORMATTER_4));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(ApiConst.DATE_FORMATTER_5));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(ApiConst.DATE_FORMATTER_6));

        //3.为 Long 类型配置格式化规则
        javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance);
        javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance);

        //4.日期类型转换-请求
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(ApiConst.DATE_FORMATTER_4));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(ApiConst.DATE_FORMATTER_5));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(ApiConst.DATE_FORMATTER_6));

        objectMapper.registerModule(javaTimeModule);

        //5.禁用日期作为时间戳
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        //6.禁用未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return objectMapper;
    }
}
